//
//  QHHCPFileManager.m
//  QHealthForDoctor
//
//  Created by 李志良的mac mini on 2020/4/13.
//  Copyright © 2020 李 志良. All rights reserved.
//热更新文件操作管理类

#import "QHHCPFileManager.h"
#import "QHHCPInternalPreferences.h"

@interface QHHCPFileManager ()<SSZipArchiveDelegate>

@end

@implementation QHHCPFileManager

// copy bundle 里的文件到Document文件夹下
//+(BOOL)copyBundleWWWToDocumentFilePath:(NSString*)wwwFolderName VersionName:(NSString*)versionName{
//    // 获取Document目录
//    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *docDirectory = [paths lastObject];
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@/www",wwwFolderName] ofType:nil];
//    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",wwwFolderName,versionName]];
//    NSString *WWWFolderDstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",wwwFolderName,versionName]];
//    DeBugLog(@"%@",dstPath);
//
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    BOOL isSuccess = YES;
//    BOOL isExist = [fileManager fileExistsAtPath:dstPath];
//    if (isExist==NO) {
//        NSError *error;
//        if (![fileManager createDirectoryAtPath:WWWFolderDstPath withIntermediateDirectories:YES attributes:nil error:&error]) {
//            isSuccess = NO;
//            DeBugLog(@"creat Directory Failed:%@",[error localizedDescription]);
//        }
//    }
//    NSError * err;
//    if(isSuccess && filePath){
//        [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:dstPath error:&err];
//    }
//    if(!err){//拷贝成功
//        return YES;
//    }else{//拷贝失败
//        return NO;
//    }
//}

+(BOOL)copySoundFileToDocument
{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:nil];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess  = YES;
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    if (isExist == NO) {
        NSError *error;
        if(![fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error])
        {
            isSuccess = NO;
        }
    }
    NSError *err;
    if (isSuccess && filePath) {
        [[NSFileManager defaultManager]copyItemAtPath:filePath toPath:docDirectory error:&err];
        NSLog(@"拷贝成功");
    }
    if (!err) {
        return YES;
    }else{
        return NO;
    }
}


// copy and unzip bundle 里的文件 到 Document 文件夹下
+(BOOL)copyAndUnzipBundleWWWToDocumentFilePath:(NSString *)wwwFolderName VersionName:(NSString*)versionName
{
    // 获取Document目录
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@/www",wwwFolderName] ofType:nil];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",wwwFolderName,versionName]];
    NSString *WWWFolderDstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",wwwFolderName,versionName]];
    DeBugLog(@"%@",dstPath);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = YES;
    BOOL isExist = [fileManager fileExistsAtPath:dstPath];
    if (isExist==NO) {
        NSError *error;
        if (![fileManager createDirectoryAtPath:WWWFolderDstPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            isSuccess = NO;
            DeBugLog(@"creat Directory Failed:%@",[error localizedDescription]);
        }
    }
    NSError * err;
    if(isSuccess && filePath){
        [fileManager copyItemAtPath:filePath toPath:dstPath error:&err];
    }
    if(!err){
        //拷贝成功
        // 去找指定文件路径下的文件解压。
        // customer
        NSString *zipFilePath1 = [dstPath stringByAppendingPathComponent:@"build/main.css.zip"];
        NSString *zipFilePath2 = [dstPath stringByAppendingPathComponent:@"build/main.js.zip"];
        NSString *zipFilePath3 = [dstPath stringByAppendingPathComponent:@"build/vendor.js.zip"];
        NSArray *pathArr = @[zipFilePath1,zipFilePath2,zipFilePath3];
        for (NSString *tempPath in pathArr) {
            if ([fileManager fileExistsAtPath:tempPath]) {
                NSString *newFolderPath = [dstPath stringByAppendingPathComponent:@"build"];
                QHHCPFileManager *hcpManager = [[QHHCPFileManager alloc]init];
                [hcpManager unzipFileatPath:tempPath andToPath:newFolderPath];
                
                NSError *deleteErr = nil;
                [fileManager removeItemAtPath:tempPath error:&deleteErr];
                DeBugLog(@"%@",deleteErr.domain);
            }
        }
        // networknurse
        NSString *zipFilePath4 = [dstPath stringByAppendingPathComponent:@"vendor.js.zip"];
        NSString *zipFilePath5 = [dstPath stringByAppendingPathComponent:@"main.js.zip"];
        NSArray *pathArr2 = @[zipFilePath4,zipFilePath5];
        for (NSString *tempPath in pathArr2) {
            if ([fileManager fileExistsAtPath:tempPath]) {
                QHHCPFileManager *hcpManager = [[QHHCPFileManager alloc]init];
                [hcpManager unzipFileatPath:tempPath andToPath:dstPath];
                NSError *deleteErr = nil;
                [fileManager removeItemAtPath:tempPath error:&deleteErr];
                DeBugLog(@"%@",deleteErr.domain);
            }
        }
        return YES;
    }
    else
    {//拷贝失败
        return NO;
    }
    return isSuccess;
}

-(BOOL)unzipFileatPath:(NSString *)fromPath andToPath:(NSString *)toPath
{
    BOOL result = NO;
    NSError *unzipError = nil;
    result = [SSZipArchive unzipFileAtPath:fromPath toDestination:toPath preserveAttributes:YES overwrite:YES password:UnZipPassWord error:&unzipError delegate:self];
    if (unzipError)
    {
        result = NO;
        DeBugLog(@"%@",unzipError.domain);
    }else{
        result = YES;
    }
    return result;
}

+(BOOL)copyCurrentWWWToNewVersionFilePath:(NSString*)wwwFolderName VersionName:(NSString*)versionName{
    // 获取Document目录
    QHHCPInternalPreferences * hcpPreferences = [QHHCPInternalPreferences loadFromUserDefaultsWithFolderName:wwwFolderName];
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *filePath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",wwwFolderName,hcpPreferences.currentReleaseVersionName]];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",wwwFolderName,versionName]];
    NSString *WWWFolderDstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@",wwwFolderName,versionName]];
    
    DeBugLog(@"%@",dstPath);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = YES;
    BOOL isExist = [fileManager fileExistsAtPath:dstPath];
    if (isExist==NO) {
        NSError *error;
        if (![fileManager createDirectoryAtPath:WWWFolderDstPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            isSuccess = NO;
            DeBugLog(@"creat Directory Failed:%@",[error localizedDescription]);
        }
    }
    
    NSError * err;
    if(isSuccess){
        [fileManager copyItemAtPath:filePath toPath:dstPath error:&err];
    }
    
    if(!err){//拷贝成功
        return YES;
    }else{//拷贝失败
        return NO;
    }
}

+(NSString*)localDowloadFilePathWithFolderName:(NSString*)folderName{
    NSString * updateFilePath;
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/Update",folderName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isSuccess = YES;
    BOOL isExist = [fileManager fileExistsAtPath:dstPath];
    if (isExist==NO) {
        NSError *error;
        if (![fileManager createDirectoryAtPath:dstPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            isSuccess = NO;
            DeBugLog(@"creat Directory Failed:%@",[error localizedDescription]);
        }
    }else{
        updateFilePath = dstPath;
    }
    if(isSuccess){
        updateFilePath = dstPath;
    }
    
    return updateFilePath;
}

+(NSString*)localDowloadFilePathWithRemoteFileLink:(NSString*)remoteFileLink{
    NSString * updateFilePath;
    NSString * linkSufix = [remoteFileLink componentsSeparatedByString:@"://"][1];
    NSString * H5FilePrifix = [linkSufix componentsSeparatedByString:@"www"][0];
    NSString * bufferedFilePath = [NSString stringWithFormat:@"BufferedFile/%@",H5FilePrifix];
    NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentDir stringByAppendingPathComponent:bufferedFilePath];
    if(filePath){
        updateFilePath = filePath;
    }
    return updateFilePath;
}

+(NSString*)getTempDownloadFilePathWithWWWContentFolderName:(NSString*)wwwContentFolderName{
    NSString * tempFilePath;
    NSString * bufferedFilePath = [NSString stringWithFormat:@"BufferedFile/qyi-oss.oss-cn-beijing.aliyuncs.com/%@",wwwContentFolderName];
    NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentDir stringByAppendingPathComponent:bufferedFilePath];
    if(filePath){
        tempFilePath = filePath;
    }
    return tempFilePath;
}

+(void)clearTempDownloadFileWithPath:(NSString*)tempFilePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager  removeItemAtPath:tempFilePath error:nil];
}

+(NSString*)localStartFileForResource:(NSString*)resourcepath wwwFolderName:(NSString*)wwwFolderName{
    NSString * startFilePath;
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    QHHCPInternalPreferences * hcpPreferences = [QHHCPInternalPreferences loadFromUserDefaultsWithFolderName:wwwFolderName];

    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",wwwFolderName,hcpPreferences.currentReleaseVersionName]];
    if([[NSFileManager defaultManager] fileExistsAtPath:dstPath]){
        DeBugLog(@"文件夹已存在");
        
        NSMutableArray* directoryParts = [NSMutableArray arrayWithArray:[resourcepath componentsSeparatedByString:@"/"]];
        NSString* filename = [directoryParts lastObject];
        startFilePath = [dstPath stringByAppendingPathComponent:filename];
    }else{
        NSError *error;
        if (![[NSFileManager defaultManager] createDirectoryAtPath:dstPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            DeBugLog(@"creat Directory Failed:%@",[error localizedDescription]);
        }else{
            NSMutableArray* directoryParts = [NSMutableArray arrayWithArray:[resourcepath componentsSeparatedByString:@"/"]];
            NSString* filename = [directoryParts lastObject];
            startFilePath = [dstPath stringByAppendingPathComponent:filename];
        }
    }
    return startFilePath;
}

+(NSString*)localWWWFolderPathWithWWWFolderName:(NSString*)wwwFolderName VersionName:(NSString*)versionName{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/",wwwFolderName,versionName]];
    NSString * filePathString = [NSString stringWithFormat:@"%@/",dstPath];
    return filePathString;
}

@end
